<template>
  <el-main class="pressure-meter-page">
    <!-- 添加加载状态 -->
    <el-row v-if="loading" justify="center" align="middle" style="height: 200px;">
      <el-col :span="24" class="text-center">
        <el-spin class="loading-spinner">
          <el-icon class="is-loading"><Loading /></el-icon>
          <div>加载中...</div>
        </el-spin>
      </el-col>
    </el-row>

    <!-- 数据加载完成后显示内容 -->
    <el-row v-else :gutter="24" class="card-container">
      <!-- 表卡片 -->
      <el-col
        :span="6"
        v-for="(meter, index) in filteredMeters"
        :key="meter?.meterId || index"
        class="card-col"
      >
        <el-card class="meter-card" shadow="hover">
          <div class="card-header">
            <h3>{{ meter?.alias || '未命名' }}</h3>
          </div>
          
          <div class="card-body">
            <el-descriptions :column="1" border class="meter-value">

              <template v-if="meter.aiValue">
                <el-descriptions-item 
                  :label="getFirstLabel(meter.aiValue)"
                >
                  <span class="value">{{ getFirstValue(meter.aiValue) }}</span>
                </el-descriptions-item>
              </template>
              
              <el-descriptions-item v-else label="识别结果">
                <span class="no-data">暂无数据</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="card-footer">
            <el-button type="primary" size="large" @click="openDetailDialog(meter)">详细</el-button>
<!--            <el-button type="success" size="large" @click="openEditDialog(meter)">编辑</el-button>-->
          </div>
        </el-card>
      </el-col>
      <!-- 新增卡片 -->
      <el-col :span="6" class="card-col">
        <el-card class="add-card" @click="openCreateDialog">
          <div class="add-icon">+</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗组件 -->
    <!-- 编辑弹窗 -->
    <EditDialog
        :visible="editDialogVisible"
        :alias="selectedMeter.alias"
        @save="updateAlias"
        @close="closeEditDialog"
    />

    <!-- 详细弹窗 -->
    <DetailDialog_txt
        :visible="detailDialogVisible"
        :meterId="selectedMeter.meterId"
        :alias="selectedMeter.alias"
        :unit="selectedMeter.unit"
        :AiRes="JSON.stringify(selectedMeter.aiValue)"
        :imgRes="selectedMeter.image_path"
        :type="currentType"
        :monitorId="selectedMeter.monitorId"
        @update:visible="detailDialogVisible = $event"
        @update:AiRes="updateAiRes"
        @update:imgRes="updateImgRes"
        @refresh="fetchAllMeters"
    />


    <!-- 新建监控弹窗 -->
    <!--    新建表-->
    <CreateMeterDialog
        :visible="createDialogVisible"
        :type="currentType"
        @update:visible="createDialogVisible = $event"
        @create="handleCreateMeter"
    />
  </el-main>
</template>

<script>
import { Loading } from '@element-plus/icons-vue'
import Card from "../components/Card.vue";
import EditDialog from "../components/EditDialog.vue";
import DetailDialog_txt from "../components/DetailDialog_txt.vue";
import CreateMeterDialog from "../components/CreateMeterDialog.vue";
import {
  getAllMeters,
  queryMeter,
  createMeter,
  updateMeterAlias, getMeterDetails
} from "../api/meter";

export default {
  name: "AmmeterPage",
  components: {
    Loading,
    Card,
    EditDialog,
    DetailDialog_txt,
    CreateMeterDialog
  },
  data() {
    return {
      loading: true, // 添加loading状态
      meters: [],
      filteredMeters: [],
      editDialogVisible: false,
      detailDialogVisible: false,
      createDialogVisible: false,
      selectedMeter: {},
      currentType: "Ammeter"
    };
  },
  methods: {
    //刷新之后更新数据
    updateAiRes(newAiRes) {
      this.selectedMeter.aiValue = newAiRes; // 更新父组件的数据
      this.selectedMeter.AiRes = JSON.stringify(newAiRes); // 确保父组件的 AiRes 属性也是更新的
    },
    updateImgRes(newImgRes) {
      this.selectedMeter.image_path = newImgRes; // 更新父组件的数据
      this.selectedMeter.imgRes = newImgRes; // 确保父组件的 imgRes 属性也是更新的
    },
    // 初始化数据
    async fetchAllMeters() {
      this.loading = true;
      try {
        const response = await getAllMeters(this.currentType);
        if (response && response.data) {
          // 确保数据是数组
          this.meters = Array.isArray(response.data) ? response.data : [response.data];
          this.filteredMeters = [...this.meters];
        } else {
          this.meters = [];
          this.filteredMeters = [];
          this.$message.warning('暂无数据');
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
        this.meters = [];
        this.filteredMeters = [];
      } finally {
        this.loading = false;
      }
    },

    // 编辑功能
    async updateAlias(newAlias) {
      try {
        await updateMeterAlias(this.selectedMeter.meterID, newAlias);
        const meterIndex = this.meters.findIndex(
            (meter) => meter.meterID === this.selectedMeter.meterID
        );
        if (meterIndex !== -1) {
          this.meters[meterIndex].alias = newAlias;
          this.filteredMeters = [...this.meters];
        }
        this.$message.success("更新成功");
        this.closeEditDialog();
      } catch (error) {
        this.$message.error("更新失败");
      }
    },

    // 弹窗控制
    openEditDialog(meter) {
      this.selectedMeter = { ...meter };
      this.editDialogVisible = true;
    },
    closeEditDialog() {
      this.editDialogVisible = false;
    },
    //详情弹窗
    async openDetailDialog(meter) {
      this.selectedMeter = {...meter};
      this.detailDialogVisible = true;
      console.log("meterid", meter.meterId); // 打印 meterId
      // 确认 meterId 仍然有效
      if (!meter.meterId) {
        this.$message.error('meterId 无效，无法获取详情');
        return;
      }
      try {
        // 打印即将传递给 getMeterDetails 的参数
        console.log('getMeterDetails 参数', meter.meterId, this.currentType);
        const details = await getMeterDetails(meter.meterId, this.currentType);
        if (details && details.data) {
          Object.assign(this.selectedMeter, details.data);
          console.log("获取的详情数据details", details);
          console.log("把详情数据加入this.selectedMeter", this.selectedMeter);
        } else {
          console.error("获取详情数据失败或数据为空", details);
        }
      } catch (error) {
        this.$message.error('获取详情失败');
        console.error("获取详情失败", error);
      }
    },


    openCreateDialog() {
      this.createDialogVisible = true;
    },

    // 创建新表
    async handleCreateMeter(meterData) {
      try {
        const createdMeter = await createMeter(
          meterData.alias,
          meterData.type
        );
        
        // 创建成功后直接刷新数据
        await this.fetchAllMeters();
        
        this.$message.success("创建成功");
        this.createDialogVisible = false;
      } catch (error) {
        console.error("创建失败:", error);
        this.$message.error("创建失败");
      }
    },

    // 解析电表数据的方法
    parseAiValue(aiValue) {
      try {
        // 首先尝试解析JSON字符串
        let parsed = typeof aiValue === 'string' ? JSON.parse(aiValue) : aiValue;
        
        // 解码键值对
        let decoded = {};
        for (let key in parsed) {
          try {
            // 直接使用原始的 key，不进行 URI 解码
            let decodedKey = key;
            // 移除前导零并保留两位小数
            let value = String(parsed[key]).replace(/^0+/, '') || '0'; // 如果全是0，保留一个0
            decoded[decodedKey] = value;
          } catch (e) {
            console.warn('处理键值对时出现警告:', e);
            decoded[key] = parsed[key];
          }
        }
        return decoded;
      } catch (error) {
        console.warn('解析AI值失败:', error);
        return {};
      }
    },



    // 格式化数值显示
    formatValue(value) {
      try {
        // 只移除前导零
        return value.replace(/^0+/, '');
      } catch (error) {
        console.error('格式化数值失败:', error);
        return value;
      }
    },

    // 获取第一个标签
    getFirstLabel(aiValue) {
      try {
        const decoded = this.parseAiValue(aiValue);
        const firstKey = Object.keys(decoded)[0];
        return '正向有功总电能';
      } catch (error) {
        console.warn('获取第一个标签失败:', error);
        return '识别结果';
      }
    },

    // 获取第一个值
    getFirstValue(aiValue) {
      try {
        const decoded = this.parseAiValue(aiValue);
        const firstValue = Object.values(decoded)[0];
        if (firstValue) {
          const [value, timestamp] = firstValue.split('$'); // 分割数值和时间戳
          return `${value} kWh`; // 返回格式化后的字符串
        }
        return '暂无数据';
      } catch (error) {
        console.warn('获取第一个值失败:', error);
        return '暂无数据';
      }
    }
  },
  async mounted() {
    await this.fetchAllMeters();
  }
};
</script>

<style scoped>
.pressure-meter-page {
  padding: 24px;
  background-color: var(--el-bg-color-page);
}

.card-container {
  max-width: 1400px;
  margin: 0 auto;
}

.card-col {
  margin-bottom: 24px;
}

.meter-card {
  height: 250px;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
}

.meter-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.loading-spinner {
  text-align: center;
}

.loading-spinner .el-icon {
  font-size: 30px;
  margin-bottom: 10px;
}

.text-center {
  text-align: center;
}

.meter-value {
  margin: 0 auto;  /* 居中显示 */
  width: 200px;    /* 设置固定宽度 */
}

.meter-value :deep(.el-descriptions) {
  width: 100%;
}

.meter-value :deep(.el-descriptions__cell) {
  padding: 0;
}

.meter-value :deep( .el-descriptions__label) {
  background-color: var(--el-fill-color-light);
  font-size: 14px;
  color: var(--el-text-color-regular);
  padding: 6px 10px;
  text-align: center;
  width: 120px;  /* 设置固定宽度而不是百分比 */
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}

.meter-value :deep(.el-descriptions__content) {
  text-align: center;
  padding: 6px 10px;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 80px;  /* 设置固定宽度而不是百分比 */
}

.meter-card .meter-value :deep(.value) {
  font-size: 14px !important;
  font-weight: 500 !important;
  color: var(--el-text-color-primary) !important;
  overflow: hidden !important; 
  text-overflow: ellipsis !important;
  white-space: nowrap !important;  /* 强制一行显示 */
  display: block !important;  /* 改为 block 显示 */
  max-width: 100% !important;
  line-height: 1.4 !important;
}

.no-data {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  font-weight: normal;
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 超出部分用省略号表示 */
  display: -webkit-box; /* 使用弹性盒子布局 */
  -webkit-box-orient: vertical; /* 垂直排列 */
  -webkit-line-clamp: 2; /* 限制为两行 */
  line-clamp: 2; /* 标准属性 */
}

.card-body {
  padding: 20px;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center; /* 居中内容 */
}

.add-card {
  width: 100%;
  height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 2px dashed var(--el-color-primary);
  background-color: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.add-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-color: var(--el-color-primary-light-3);
}

.add-icon {
  font-size: 24px;
  color: #1890ff;
}

.card-footer {
  padding: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: auto;
}

.card-footer :deep(.el-button) {
  min-width: 90px;
  padding: 12px 20px;
  font-size: 14px;
  font-weight: 500;
}

.card-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  text-align: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
  font-weight: 500;
  line-height: 1.4;
}

.meter-card {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.value {
  width: 100%; /* 设置宽度为100% */
  margin: 0; /* 去掉左右的边距 */
  padding: 0; /* 去掉左右的填充 */
  box-sizing: border-box; /* 确保填充和边框不影响宽度 */
  text-align: center; /* 如果需要，可以居中内容 */
}
</style>
